<!DOCTYPE html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <title>集合时间推算</title>

</head>

<body>

    <div id="container">

    </div>

    <div class="cardP">
        <div class="card ">

            <h2 id="addTxt"></h2>
            <div id="introP">

            </div>

        </div>


    </div>


</body>

<style type="text/css">
    #addTxt {
        display: flex;
        font-family: 微软雅黑, serif;
        font-size: 16px;
        color: #af0e66;
        font-weight: normal;
        justify-content: space-around;
        height: 50px;
    }

    .cardP {
        display: flex;
        align-items: center;
        justify-content: space-around;
    }


    #introP {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
    }

    .introItem {
        font-size: 12px;
        margin: 10px;
    }

    .card {
        overflow: hidden;
        display: grid;
        padding: 10px;
        flex-direction: column;
        width: 100%;
        position: relative;
        word-wrap: break-word;
        background-color: #fff;
        border: 1px solid #e7eaf3;
        border-radius: .5rem;
        box-shadow: 2px 2px 4px #88888822;
    }


    * {
        margin: 0;
        padding: 0;
    }

    ul {
        list-style: none;
    }

    html,
    body {
        height: 100%;
    }

    #container {
        width: 100%;
        height: 800px;
        margin: 0px;
        top: 0;
    }


    #loadingTip {
        position: absolute;
        z-index: 9999;
        top: 0;
        left: 0;
        padding: 3px 10px;
        background: red;
        color: #fff;
        font-size: 14px;
    }
</style>

<script src="https://webapi.amap.com/loader.js"></script>
<script type="text/javascript">


    AMapLoader.load({
        "key": "50fb22c2238084f1713116bf827d6635",              // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": [],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "AMapUI": {             // 是否加载 AMapUI，缺省不加载
            "version": '1.1',   // AMapUI 缺省 1.1
            "plugins": ['overlay/SimpleMarker'],       // 需要加载的 AMapUI ui插件
        },
        "Loca": {                // 是否加载 Loca， 缺省不加载
            "version": '2.0'  // Loca 版本，缺省 1.3.2
        },
    }).then((AMap) => {
        map = new AMap.Map('container', {
            zoom: 12,//级别
            center: [106.531115, 29.583326],//中心点坐标
        });

        AMap.plugin('AMap.Geocoder', function () {
            geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                batch: false,
                city: '023',

            })
        })

        AMap.plugin('AMap.Driving', function () {
            driving = new AMap.Driving({
                // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
                policy: AMap.DrivingPolicy.LEAST_TIME,
                autoFitView: false,
                hideMarkers: true,
            })
        })

        AMap.plugin('AMap.Transfer', function () {
            transfer = new AMap.Transfer({
                // 公交路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
                policy: AMap.TransferPolicy.LEAST_TIME,
                city: '023',
                autoFitView: false,
                hideMarkers: true,

            })

        })

        //加载PathSimplifier，loadUI的路径参数为模块名中 'ui/' 之后的部分
        AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) {

            if (!PathSimplifier.supportCanvas) {
                alert('当前环境不支持 Canvas！');
                return;
            }

            //启动页面
            initPage(PathSimplifier);
        });

        marker = new AMap.Marker();

        // 创建一个 icon
        var endIcon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: 'http://a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
            imageSize: new AMap.Size(135, 40),
            imageOffset: new AMap.Pixel(-95, -3)
        });

        // 将 icon 传入 marker
        marker = new AMap.Marker({
            icon: endIcon,
        });


        Init();

    }).catch((e) => {
        console.error(e);  //加载错误提示
    });

    var data = [
        ["丁阳", "时代天街E馆", false],
        ["王明胜", "鲁能星城五街区", false],
        ["孙齐逊", "元合悠哉悠宅", false],
        ["朱俊", "鲁能星城四街区", false],
        ["李作舟", "北晨丽景", false],
        ["范盛杰", "重庆市江北区五红路40号长安华都东区", false],
        // ["李文睿", "鸿恩丽舍", false],
        // ["罗佳", "龙湖U城4组团", false],
        // ["于殿文", "南纪门街道文化街37号", false],
        // ["曹黎", "广厦城巢上3期", false],
        // ["张萌莹", "同景国际城馥山", false],
        // ["程竣麟", "万友七季城", false],
        // ["杨镇铨", "南坪二塘路南滨六号2栋", false],
        // ["李萧羽", "首钢美利花都", false],
        // ["黄科", "财信·时光里", false],
        // ["胡南", "江屿朗廷", false],
        // ["沈洋", "隆鑫国际7栋", false],
        // ["张云之", "渝北银桦路125号圣地阳光", false],
        // ["罗浩云", "渝中区解放东路187号和诚大厦A", false],
        // ["陈茂莹", "渝中区解放东路187号和诚大厦A", false],
        // ["梁岚", "渝中区解放东路187号和诚大厦A", false],
        // ["陈晓", "山顶道壹号", false],
        // ["陈文瑶", "七星岗街道德兴里小区3号楼", false],
        // ["苏川铸", "东海阿特豪斯3栋", false],
        // ["王凯达", "碚都佳园D组团", false],
        // ["张瑶", "幸福时光里", false],
        // ["何瀚钊", "南方上格林紫薇苑", false],
        // ["吴镇航", "龙湖·春森彼岸1期", false],
        // ["张皓林", "大石坝康盛园2号楼", false],
        // ["邱智文", "万科观承", false],
        // ["刘抒宁", "馨茗苑", false],
        // ["王仝", "重庆富力院士廷", false],
        // ["周诚", "朗诗乐府领澜", false],
        // ["彭昱玮", "南岸区弹子石星泽汇", false],

        // ["陈灵睿", "恒基翔龙江畔", false],
        // ["马丹睿", "金刚塔小区", false],
        // ["刘鸣寰", "鲁能星城一街区", false],
        // ["尹行行", "保利九悦荟", false],
        // ["王俊翔", "鲁能星城六街区", false],
        // ["朱传福", "华融现代城", false],


    ];
    var colors = [
        "#3366cc", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
        "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
        "#651067", "#329262", "#5574a6", "#3b3eac"
    ];

    var driving;
    var transfer;

    var loaded = 0;

    var marker;

    var geocoder;

    var map;

    function Search(role, endLngLat) {
        let startLngLat = role[3];
        searchData = [];


        var isDriver = role[2];

        var idx = data.indexOf(role);
        var color = getColor(idx);


        if (isDriver) {
            driving.search(startLngLat, endLngLat, function (status, result) {
                // 未出错时，result即是对应的路线规划方案
                if (status === 'complete' && result.routes.length) {
                    var plan = result.routes[0];
                    var hour = Math.floor(plan.time / 3600);
                    var minuteStr = Math.floor(plan.time % 3600 / 60) + "分钟";
                    var timeStr = hour > 0 ? hour + "小时" + minuteStr : minuteStr;

                    var tips = role[0] + ":" + timeStr + ",驾车";
                    console.log(tips);
                    tips = "<font color=" + color + ">" + tips + "</font>";

                    var path = [];
                    for (let i = 0; i < plan.steps.length; i++) {
                        var step = plan.steps[i];
                        path = path.concat(step.path);
                    }

                    var sItem = {
                        name: tips,
                        path: path,
                        idx: idx,
                    };
                    searchData.push(sItem);

                    console.log(result)
                } else {
                    var tips = role[0] + ":太近或者太远";
                    tips = "<font color=" + color + ">" + tips + "</font>";
                    console.log(tips);
                    var sItem = {
                        name: tips,
                        path: [],
                        idx: idx,
                    };
                    searchData.push(sItem);
                }

                loaded++;
                if (loaded == data.length) {

                    SearchDone();
                    loaded = 0;
                }

            })
        } else {
            transfer.search(startLngLat, endLngLat, function (status, result) {
                console.log(result);
                if (result.info == "NO_DATA") {
                    var tips = role[0] + ":太近或者太远";
                    tips = "<font color=" + color + ">" + tips + "</font>";
                    console.log(tips);
                    var sItem = {
                        name: tips,
                        path: [],
                        idx: idx,
                    };
                    searchData.push(sItem);

                } else if (result.info == "OK") {
                    // 未出错时，result即是对应的路线规划方案
                    var plan = result.plans[0];
                    var lineNum = 0;
                    for (let i = 0; i < plan.segments.length; i++) {
                        var sm = plan.segments[i];
                        if (sm.transit_mode != "WALK") {
                            lineNum++;
                        }
                    }

                    var hour = Math.floor(plan.time / 3600);
                    var minuteStr = Math.floor(plan.time % 3600 / 60) + "分钟";
                    var timeStr = hour > 0 ? hour + "小时" + minuteStr : minuteStr;

                    var tips = role[0] + ":" + timeStr + "," + "步行约" + plan.walking_distance + "米,乘坐" + lineNum + "次公共交通";
                    tips = "<font color=" + color + ">" + tips + "</font>";

                    console.log(result);

                    var sItem = {
                        name: tips,
                        path: plan.path,
                        idx: idx,
                    };
                    searchData.push(sItem);
                }

                loaded++;
                if (loaded == data.length) {
                    SearchDone();
                    loaded = 0;
                }

            })
        }


    }

    function getColor(idx) {
        return colors[idx % colors.length]
    }

    var searchData = [];

    function SearchDone() {
        console.log("SearchDone")
        var introP = document.getElementById("introP");

        var realData = [];
        for (let i = 0; i < searchData.length; i++) {
            var data = searchData[i];

            introP.children[data.idx].innerHTML = data.name;
            // console.log(introP.children[data.idx].innerHTML);

            if (data.path.length > 0) {
                realData.push(data);
            }
        }


        introP.children[introP.children.length - 1].innerHTML = "";

        if (searchData.length < globalThis.data.length) {
            introP.children[introP.children.length - 1].innerHTML =
                "获取数据不完整" + searchData.length + "/" + globalThis.data.length + "   情重试选择标志性车站或建筑";
        }

        pathSimplifierIns.setData(realData);

        for (let i = 0; i < realData.length; i++) {
            color = getColor(realData[i].idx);

            var navg = pathSimplifierIns.createPathNavigator(i,
                {
                    loop: false, //循环播放
                    speed: 1000,
                    pathNavigatorStyle: {
                        fillStyle: "#FFFFFF",
                        strokeStyle: color,
                        borderStyle: color,
                        pathLinePassedStyle: {
                            strokeStyle: color,
                            borderStyle: color,
                        }
                    }
                });

            navg.start();
        }


        $('#loadingTip').remove();
    }

    function regeoCode(lnglat) {
        map.add(marker);
        marker.setPosition(lnglat);

        geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
                var address = result.regeocode.formattedAddress;
                document.getElementById("addTxt").textContent = address;
            } else {
                log.error('根据经纬度查询地址失败')
            }
        });
    }


    function Init() {
        var introP = document.getElementById("introP");

        for (var i = 0; i < data.length + 1; i++) {
            var item = document.createElement("div");
            item.className = "introItem";
            introP.appendChild(item);
        }
        console.log(introP.children.length);
        geoCode();
    }


    var doneIdx = 0;

    // 根据地址获取ip
    function geoCode() {
        doneIdx = 0;
        for (let i = 0; i < data.length; i++) {
            let dataItem = data[i];
            setTimeout(() => {
                this.geoOne(dataItem);
            }, i * 200);



        }

    }

    function geoOne(dataItem) {

        geocoder.getLocation(dataItem[1], function (status, result) {
            if (status === 'complete' && result.geocodes.length) {
                var gcode = result.geocodes[0];
                dataItem[3] = gcode.location;

            }
            doneIdx++;
            console.log(dataItem, doneIdx + "/" + data.length);
            drawItem(dataItem)
            if (doneIdx == data.length) {
                GeoDone();
            }
        });


    }


    function drawItem(dataItem) {
        // var pos = dataItem[3];
        // if (dict.hasOwnProperty(pos)) {
        //     dict[pos] = dict[pos] + 1;
        //     console.log(dataItem[0] + "冲突了" + dict[pos] - 1)
        //     dataItem[3].kT += 0.0001 * (dict[pos] - 1);
        //     dataItem[3].lat += 0.0001 * (dict[pos] - 1);
        // } else {
        //     dict[pos] = 1;
        // }
        // console.log(dict)

        // console.log(dd)
        // 创建纯文本标记
        var i = data.indexOf(dataItem);
        var text = new AMap.Text({
            text: dataItem[0],
            anchor: 'center', // 设置文本标记锚点
            // draggable: true,
            cursor: 'pointer',
            style: {
                // 'padding': '.75rem 1.25rem',
                'margin-bottom': '1rem',
                'border-radius': '.25rem',
                'background-color': getColor(i),
                'width': '20 rem',
                'border-width': 0,
                'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                'text-align': 'center',
                'font-size': '12px',
                'color': 'white'
            },
            position: dataItem[3]
        });
        text.setMap(map);
    }


    function GeoDone() {
        map.on('click', function (ev) {

            $('<div id="loadingTip">查询数据，请稍候...</div>').appendTo(document.body);
            // 触发事件的地理坐标，AMap.LngLat 类型
            var endLngLat = ev.lnglat;

            regeoCode(endLngLat);


            for (let i = 0; i < data.length; i++) {
                var role = data[i];
                Search(role, endLngLat);
            }
        });

        var dict = {};
        for (var i = 9; i < data.length; i++) {
            // var pos = data[i][3];
            // if (dict.hasOwnProperty(pos)) {
            //     dict[pos] = dict[pos] + 1;
            //     console.log(data[i][0] + "冲突了" + dict[pos] - 1)
            //     data[i][3].kT += 0.0001 * (dict[pos] - 1);
            //     data[i][3].lat += 0.0001 * (dict[pos] - 1);
            // } else {
            //     dict[pos] = 1;
            // }
            // console.log(dict)

        }


        for (var i = 0; i < data.length; i++) {
            // var dd = data[i];
            // // console.log(dd)
            // // 创建纯文本标记
            // console.log(dd[0], dd[3].pos)

            // var text = new AMap.Text({
            //     text: dd[0],
            //     anchor: 'center', // 设置文本标记锚点
            //     // draggable: true,
            //     cursor: 'pointer',
            //     style: {
            //         // 'padding': '.75rem 1.25rem',
            //         'margin-bottom': '1rem',
            //         'border-radius': '.25rem',
            //         'background-color': getColor(i),
            //         'width': '20 rem',
            //         'border-width': 0,
            //         'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
            //         'text-align': 'center',
            //         'font-size': '12px',
            //         'color': 'white'
            //     },
            //     position: dd[3]
            // });
            // text.setMap(map);
        }
    }

    var pathSimplifierIns;

    function initPage(PathSimplifier) {
        //创建组件实例
        pathSimplifierIns = new PathSimplifier({

            zIndex: 100,
            autoSetFitView: false,
            map: map, //所属的地图实例

            getPath: function (pathData, pathIndex) {

                return pathData.path;
            },
            getHoverTitle: function (pathData, pathIndex, pointIndex) {

                if (pointIndex >= 0) {
                    //point
                    return pathData.name;//+ '，点：' + pointIndex + '/' + pathData.path.length;
                }

                return pathData.name;//+ '，点数量' + pathData.path.length;
            },
            renderOptions: {
                pathLineStyle: {
                    dirArrowStyle: true
                },
                getPathStyle: function (pathItem, zoom) {
                    var color = getColor(pathItem.pathData.idx);
                    var isDriver = data[pathItem.pathData.idx][2];
                    lineWidth = Math.round(2 * Math.pow(1.1, zoom - 8));
                    //

                    var pathNavigatorStyle = isDriver ?
                        {
                            width: 12,
                            height: 24,
                            content: PathSimplifier.Render.Canvas.getImageContent('https://webapi.amap.com/ui/1.1/ui/misc/PathSimplifier/examples/imgs/car.png', onload, onerror),
                        } : {};

                    pathNavigatorStyle.fillStyle = color;

                    return {
                        pathLineStyle: {
                            strokeStyle: color,
                            lineWidth: lineWidth
                        },
                        pathLineHoverStyle: {
                            strokeStyle: color,
                            lineWidth: lineWidth + 2
                        },
                        pathNavigatorStyle: pathNavigatorStyle
                    };
                }
            }

        }
        )
            ;
        window.pathSimplifierIns = pathSimplifierIns;

    }

</script>